//
//  CZQVipPhotoViewController.m
//  coachmanage
//
//  Created by 众拳科技 on 2018/3/16.
//  Copyright © 2018年 众拳科技. All rights reserved.
//

#import "CZQVipPhotoViewController.h"
#import "CZQVipPhotoTableViewCell.h"
#import "CZQAddVipPhoto.h"
#import "NoDataView.h"
@interface CZQVipPhotoViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    int startIndex;
    
    int pageSize;
}
/**
 //数据源
 */
@property(nonatomic,strong)NSMutableArray *dataArr;


/**
 tableView
 */
@property(nonatomic,weak)UITableView *tableView;

@property(nonatomic,strong)NoDataView *noDataView;



@end

@implementation CZQVipPhotoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"会员照片";
    
    self.view.backgroundColor = BackGroundColor;
    
    UIBarButtonItem *rightButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"icon_navadd"]
                                                                               imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(rightBtnClick)];
    self.navigationItem.rightBarButtonItem = rightButtonItem;
    
    [self tableView];
}

#pragma mark 下拉
-(void)loadStartData{
    
    startIndex = 1;
    
    pageSize = 20;
    
    [self loadData];
}

#pragma mark 上拉
-(void)loadMoreData{
    
    startIndex = startIndex + 1;
    
    [self loadData];
}


-(void)loadData{
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    
    
    [params setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"ShopID"] forKey:@"ShopID"];
    
    [params setObject:[NSString stringWithFormat:@"%d",startIndex] forKey:@"page"];
    
    [params setObject:[NSString stringWithFormat:@"%d",pageSize] forKey:@"rows"];
    
    [HTTPTool GET:Get_GetMemberShopPic_List parameters:params
     
          success:^(id responseObject){
              
              [MBProgressHUD hideHUDForView:self.view];
              
              if (responseObject && [[responseObject objectForKey:@"Code"] intValue] == 0) {
                  
                  NSMutableArray *resultArray = [responseObject objectForKey:@"rows"];
                  
                  if (resultArray.count > 0) {
                      
                      [self.tableView.mj_header endRefreshing];
                      
                      [self.tableView.mj_footer endRefreshing];
                  }
                  else{
                      
                      [self.tableView.mj_header endRefreshing];
                      
                      [self.tableView.mj_footer endRefreshingWithNoMoreData];
                  }
                  
                  self.noDataView = [NoDataView shareInstance];
                  
                  [self.noDataView hideInView:self.view];
                  
                  if (startIndex == 1) {
                      
                      self.dataArr = [NSMutableArray arrayWithArray:resultArray];
                      
                      if (self.dataArr.count == 0) {
                          
                          self.noDataView = [NoDataView shareInstance];
                          
                          [self.noDataView showInView:self.view];
                      }
                  }
                  else{
                      
                      [self.dataArr addObjectsFromArray:resultArray];
                  }
                  
                  
                  
                  [self.tableView reloadData];
              }
              
          }
     
          failure:^(NSError *error){
              
              [self.tableView.mj_header endRefreshing];
              
              self.noDataView = [NoDataView shareInstance];
              
              [self.noDataView showInView:self.view];
              
              [MBProgressHUD hideHUDForView:self.view];
          }];
}


#pragma mark -- 懒加载

-(NSMutableArray *)dataArr
{
    if (!_dataArr) {
        
        _dataArr = [NSMutableArray array];
        
    }
    
    return _dataArr;
}

-(UITableView *)tableView
{
    if (!_tableView) {
        
        UITableView *tableView=[[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        
        tableView.delegate=self;
        
        tableView.dataSource=self;
        
        
        tableView.estimatedRowHeight = 50;
        
        [self.view addSubview:tableView];
        
        [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.edges.mas_equalTo(self.view);
            
        }];
        
        //        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        
        //注册
        //                [tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
        
        [tableView registerNib:[UINib nibWithNibName:@"CZQVipPhotoTableViewCell" bundle:nil]  forCellReuseIdentifier:@"cell"];
        

        MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        footer.automaticallyHidden = YES;
        
        MyTableHead *mj_head = [MyTableHead headerWithRefreshingTarget:self refreshingAction:@selector(loadStartData)];
        tableView.mj_header = mj_head;
        tableView.mj_footer = footer;
        [tableView.mj_header beginRefreshing];
        [tableView mas_remakeConstraints:^(MASConstraintMaker *make) {
            
            make.edges.mas_equalTo(self.view);
            
        }];
        
        _tableView = tableView;
    }
    return _tableView;
}

#pragma mark - UITableViewDataSource

//行数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

//列数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArr.count;
}

//cell内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CZQVipPhotoTableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    CZQAddVipPhoto *model = [CZQAddVipPhoto mj_objectWithKeyValues:[self.dataArr objectAtIndex:indexPath.row]];
    
    cell.coachNameLable.text = model.AddUserName;
    
    cell.timeLable.text = model.AddTime;
    
    [cell.vipPhotoImage sd_setImageWithURL:[Helper imageUrlStringToChinese:model.Path imageType:nil] placeholderImage:PlaceHold];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell  ;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.00001;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.00001;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return [[UIView alloc]initWithFrame:CGRectZero];
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return [[UIView alloc]initWithFrame:CGRectZero];
}



-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //当离开某行时，让某行的选中状态消失
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}

#pragma mark - 添加会员照片

-(void)rightBtnClick
{
    
    [self logoSelect];
    
}

#pragma mark - 图片选择

-(void)logoSelect{
    
    
    WS(weakSelf);
    
    ZLPhotoPickerViewController *pickerVc = [[ZLPhotoPickerViewController alloc] init];
    
    pickerVc.maxCount = 1;
    
    // Jump AssetsVc
    pickerVc.status = PickerViewShowStatusCameraRoll;
    // Recoder Select Assets
    //    pickerVc.selectPickers = self.assets;
    // Filter: PickerPhotoStatusAllVideoAndPhotos, PickerPhotoStatusVideos, PickerPhotoStatusPhotos.
    
    pickerVc.photoStatus = PickerPhotoStatusPhotos;
    // Desc Show Photos, And Suppor Camera
    pickerVc.isShowCamera = YES;
    pickerVc.topShowPhotoPicker = YES;
    
    // CallBack
    
    pickerVc.callBack = ^(NSArray<ZLPhotoAssets *> *status){
        
        for (ZLPhotoAssets *assets in status) {
            
            ZLPhotoPickerBrowserPhoto *photo = [ZLPhotoPickerBrowserPhoto photoAnyImageObjWith:assets];
            
            photo.asset = assets;
            
            
            UIImage *image;
            
            
            
            
            
            //拍照
            if ([photo.asset isKindOfClass:[UIImage class]]) {
                
                image = (UIImage *)photo.asset;
            }
            else{
                
                image = [assets thumbImage];
                
            }
            
            
            
            
            [weakSelf uploadImage:image];
            
            break;
        }
    };
    
    [pickerVc showPickerVc:self];
    
}

#pragma mark 上传头像
-(void)uploadImage:(UIImage *)image{
    
    if (!image) {
        
        return;
    }
    
    
    WS(weakSelf);
    
    NSData *imageData  = UIImageJPEGRepresentation(image,0.1);
    
    [MBProgressHUD showMessage:@"上传中.." toView:self.view];
    
    RAYUploader *upload = [RAYUploader defaultUploader];
    
    [upload uploadWithData:imageData complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        
        
        
        if (key) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                NSString *picUrl = [NSString stringWithFormat:@"%@%@",QiNiuBase,key];
                
                //添加图片
                NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
                
                
                [params setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"ShopID"] forKey:@"ShopID"];
                
                [params setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"UserID"] forKey:@"MemberID"];
                
                [params setObject:picUrl forKey:@"Path"];
                
                [params setObject:weakSelf.venueVipModel.MemberID forKey:@"AddUserID"];
                
                [params setObject:weakSelf.venueVipModel.Name forKey:@"AddUserName"];
                
                
                [params setObject:[NSString stringWithFormat:@"%d",pageSize] forKey:@"rows"];
                [HTTPTool POSTRaw:Post_MemberShopPicOperate parameters:params success:^(id responseObject) {
                    [MBProgressHUD hideHUDForView:weakSelf.view];
                    
                    if (responseObject && [[responseObject objectForKey:@"Code"] intValue] == 0) {
                        
                        
                        [weakSelf loadData];
                        
                    }
                    
                    
                } failure:^(NSError *error) {
                    
                    [MBProgressHUD hideHUDForView:self.view];
                    
                }];
                
            });
            
        }
        
    }];
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
